package com.kkd.kkdapp.activity;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.kkd.kkdapp.R;
import com.kkd.kkdapp.base.BaseActivity;
import com.kkd.kkdapp.http.manager.HttpCallBack;
import com.kkd.kkdapp.http.manager.KkdHttpMagager;
import com.kkd.kkdapp.listener.OnSingleClickListener;
import com.kkd.kkdapp.particle2.ParticleSystem;
import com.kkd.kkdapp.utils.DialogUtils;
import com.kkd.kkdapp.utils.PreferenceUtils;
import com.kkd.kkdapp.utils.SystemUtils;

/**
 * 投标成功
 * 
 * @author mty
 */
public class TreatySucceedActivity extends BaseActivity implements
		OnClickListener {

	public static final int CLOSE_RESULT_CODE = 10001;
	public static final int CONTINUE_CODE = 10002;
	public static final int VIEW_RECORD_CODE = 10003;
	public static final int RETURN_CODE = 10004;
	public static final int BACK_CODE = 10005;
	private static final int CAMPAIGN_SUCCESS = 1;

	private Dialog dialog_finishShoutou;
	private RelativeLayout draw_lottery_rl; // 摇奖机会
	private String url; // 摇奖机会跳转Url
	private String poiId;
	private int productType;
	private double tenderAmout;
	private TextView hint_tv;
	private TextView title_tv;
	private Button continue_bt; // 继续投标
	private TextView examine; // 　查看记录
	private RelativeLayout result_title_img; // 完成
	private TextView bidname; // 标的名字
	private TextView tenderamount; // 投标金额
	private TextView biddeadline_company; // 投资期限单位
	private TextView expected_return_tv; // 预计收益
	private TextView repayment_tv; // 还款方式
	private TextView startInterest_tv; // 开始计息
	private TextView expectedInterest_tv; // 预计计息TextView
	private RelativeLayout result_title;
	private LinearLayout main_layout;

	private Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case CAMPAIGN_SUCCESS: // 投标成功活动请求成功
				try {
					String customerIdAndToken = PreferenceUtils.getInstance()
							.getcustomerId(TreatySucceedActivity.this);
					final String[] cat = customerIdAndToken.split("&");
					Object responseBody = msg.obj;
					String reponString = responseBody.toString();
					final JSONObject data = new JSONObject(reponString);
					boolean popUp = data.optBoolean("popUp");
					final int isLuckyFlag = data.optInt("isLuckyFlag");
					String mis_succ_image = data.optString("mis_succ_image");// 是否首投开启特权
					if (isLuckyFlag == 1) {
						String luckyUrl = data.getString("luckyUrl");
						url = luckyUrl + "&customerId=" + cat[1] + "&token="
								+ cat[0] + "&channel=Android";
						draw_lottery_rl.setVisibility(View.VISIBLE);
						main_layout.setBackgroundColor(Color
								.parseColor("#f0eef3"));
						mHandler.postDelayed(new Runnable() {

							@Override
							public void run() {
								// 设置粒子扩散效果
								ParticleSystem particleSystem = new ParticleSystem(
										TreatySucceedActivity.this, 100,
										R.drawable.sign, 800);
								particleSystem
										.setContext(TreatySucceedActivity.this);
								particleSystem.setSpeedRange(0.025f, 0.045f)
										.oneShot(findViewById(R.id.shake_icon),
												50);
							}
						}, 1000);
					}
					if (TextUtils.isEmpty(mis_succ_image)) {// 说明不是首投，走以前的逻辑
						if (popUp) {
							// 签到完成状态，0未完成，1完成；
							int signInStatus = data.getInt("signInStatus");
							// 签到获取快乐币个数
							int signInCionSum = data.getInt("signInCionSum");
							// 签到优惠券金额
							long signIncouponAmount = data
									.getLong("signIncouponAmount");
							// 连续签到天数
							int days = data.getInt("days");
							// 分享邀请好友获得快乐币个数
							int inviteCionSum = data.getInt("inviteCionSum");
							// 0未完成，1完成；
							int inviteStatus = data.getInt("inviteStatus");
							// 投资完成状态，0未完成，1完成；
							int poiStatus = data.getInt("poiStatus");
							// 投资奖励快乐币个数
							int poiCionSum = data.getInt("poiCionSum");
							// 投资任务未完成提示最高奖励快乐币个数
							int poiMoreCionSum = data.getInt("poiMoreCionSum");
							// 邀请好友攻略Url
							String inviteStrategyUrl = data
									.getString("inviteStrategyUrl");
							// 快乐币任务全部完成获取快乐币总数
							int doubleAllSum = data.getInt("doubleAllSum");
							// 完成快乐币任务排名
							int customerSeat = data.getInt("customerSeat");
							// 完成任务获得快乐币个数
							int doubleSum = data.getInt("doubleSum");
							// 完成快乐币任务翻倍的倍率
							String doubleRate = data.getString("doubleRate");
							// 翻倍获取快乐币个数
							int doubleMisSum = data.getInt("doubleMisSum");
							// 快乐币任务url
							String coinMisUrl = data.getString("coinMisUrl");
							// 是否可以补签 0：不可以，1：可以
							int isRepairSigninStatus = data
									.getInt("isRepairSigninStatus");
							happyCoinCompleteProgressDialog(signInStatus,
									signInCionSum, signIncouponAmount, days, 3,
									inviteCionSum, inviteStatus, poiStatus,
									poiCionSum, poiMoreCionSum,
									inviteStrategyUrl, doubleAllSum,
									customerSeat, doubleSum, doubleRate,
									doubleMisSum, coinMisUrl,
									isRepairSigninStatus);
						}
					} else {
						if (dialog_finishShoutou != null) {
							dialog_finishShoutou.cancel();
							dialog_finishShoutou = null;
						}
						final String moneyTreeUrl = data
								.optString("moneyTreeUrl");
						dialog_finishShoutou = DialogUtils
								.finishXinshouShoutouDialog(
										TreatySucceedActivity.this,
										mis_succ_image,
										new OnSingleClickListener() {

											@Override
											public void onSingleClick(View v) {
												if (dialog_finishShoutou != null) {
													dialog_finishShoutou
															.cancel();
												}
												if (!TextUtils
														.isEmpty(moneyTreeUrl)) {
													Intent intent = new Intent(
															TreatySucceedActivity.this,
															KKDWebActivity.class);
													intent.putExtra(
															"url",
															moneyTreeUrl
																	+ "&customerId="
																	+ cat[1]
																	+ "&token="
																	+ cat[0]
																	+ "&channel=Android");
													startActivity(intent);
												}
											}
										});
						dialog_finishShoutou.show();
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
				break;
			}
		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.tendersucceedresult);
		initView();
		setListener();
		getMessage();
		tenderAffirmCampaign();
	}

	/**
	 * 初始化控件
	 */
	public void initView() {

		draw_lottery_rl = (RelativeLayout) this
				.findViewById(R.id.draw_lottery_rl);
		hint_tv = (TextView) this.findViewById(R.id.hint_tv);
		title_tv = (TextView) this.findViewById(R.id.title_tv);
		continue_bt = (Button) this.findViewById(R.id.continue_bt);
		continue_bt.setPadding(0, 0, 0, 0);
		examine = (TextView) this.findViewById(R.id.examine);
		result_title_img = (RelativeLayout) this
				.findViewById(R.id.result_title_img);
		bidname = (TextView) this.findViewById(R.id.bidname);
		tenderamount = (TextView) this.findViewById(R.id.tenderamount);
		biddeadline_company = (TextView) this
				.findViewById(R.id.biddeadline_company);
		expected_return_tv = (TextView) this
				.findViewById(R.id.expected_return_tv);
		repayment_tv = (TextView) this.findViewById(R.id.repayment_tv);
		startInterest_tv = (TextView) this.findViewById(R.id.startInterest_tv);
		result_title = (RelativeLayout) this.findViewById(R.id.result_title);
		main_layout = (LinearLayout) this.findViewById(R.id.main_layout);
		main_layout.setBackgroundColor(Color.parseColor("#FFFFFF"));
		expectedInterest_tv = (TextView) this
				.findViewById(R.id.expectedInterest_tv);
		if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
			android.widget.LinearLayout.LayoutParams parms = (android.widget.LinearLayout.LayoutParams) result_title
					.getLayoutParams();
			parms.height = SystemUtils.dip2px(this, 50);
			result_title.setLayoutParams(parms);
		}

	}

	/**
	 * 注册监听事件
	 */
	public void setListener() {
		draw_lottery_rl.setOnClickListener(this);
		continue_bt.setOnClickListener(this);
		examine.setOnClickListener(this);
		result_title_img.setOnClickListener(this);
	}

	/****
	 * 获取上个界面传值
	 */
	public void getMessage() {
		Intent intent = this.getIntent();
		poiId = intent.getStringExtra("poiId");
		productType = intent.getIntExtra("productType", -1);
		tenderAmout = intent.getDoubleExtra("tenderAmout", 0);
		String title = intent.getStringExtra("title");
		hint_tv.setText(title);
		title_tv.setText(title);
		String continue_bt_tx = intent.getStringExtra("continue_bt_tx");
		continue_bt.setText(continue_bt_tx);
		boolean examineFlag = intent.getBooleanExtra("examineFlag", true);
		String button_tv = intent.getStringExtra("button_tv");
		if (examineFlag) {
			examine.setVisibility(View.VISIBLE);
		} else {
			examine.setVisibility(View.GONE);
		}
		examine.setText(button_tv);
		String bidName = intent.getStringExtra("bidName"); // 标的名字
		bidname.setText(bidName);
		// 投标金额
		String tenderAmoutStr = intent.getStringExtra("tenderAmoutStr");
		tenderamount.setText(tenderAmoutStr);
		// 投资期限
		int bidPeriodAdd = intent.getIntExtra("bidPeriodAdd", 0);
		int bidDeadline = intent.getIntExtra("bidDeadline", 0);
		String bidDeadline_company = intent
				.getStringExtra("bidDeadline_company");
		TextView biddeadline = (TextView) this.findViewById(R.id.biddeadline);
		TextView biddeadline_company1 = (TextView) this
				.findViewById(R.id.biddeadline_company1);
		TextView biddeadline1 = (TextView) this.findViewById(R.id.biddeadline1);
		if (bidPeriodAdd == 0) {
			biddeadline.setText(bidDeadline + "");
			biddeadline_company1.setVisibility(View.GONE);
			biddeadline1.setVisibility(View.GONE);
		} else {
			biddeadline_company1.setVisibility(View.VISIBLE);
			biddeadline1.setVisibility(View.VISIBLE);
			biddeadline.setText(bidDeadline + ""); // 投资期限
			biddeadline_company1.setText(bidDeadline_company + "+");
			biddeadline1.setText("" + bidPeriodAdd);
		}
		// 投资期限单位
		biddeadline_company.setText(bidDeadline_company);
		// 预计收益
		String expected_return = intent.getStringExtra("expected_return");
		expected_return_tv.setText(expected_return);
		// 还款方式
		String repayment = intent.getStringExtra("repayment");
		repayment_tv.setText(repayment);
		// 开始计息
		String startInterest = intent.getStringExtra("startInterest");
		startInterest_tv.setText(startInterest);
		String expectedInterest = intent.getStringExtra("expectedInterest");
		expectedInterest_tv.setText(expectedInterest);

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.draw_lottery_rl: // 摇奖
			if (!TextUtils.isEmpty(url)) {
				SystemUtils.onEvent("Regular_Result_GotoLotteryn", 1);
				Intent intent = new Intent(TreatySucceedActivity.this,
						KKDWebActivity.class);
				intent.putExtra("url", url);
				startActivity(intent);
				setResult(CLOSE_RESULT_CODE);
				finish();
			}
			break;
		case R.id.continue_bt: // 继续投标
			setResult(CONTINUE_CODE);
			finish();
			break;
		case R.id.examine: // 　查看记录
			setResult(VIEW_RECORD_CODE);
			finish();
			break;
		case R.id.result_title_img: // 完成
			setResult(RETURN_CODE);
			finish();
			break;

		}

	}

	// 投标成功活动
	public void tenderAffirmCampaign() {
		String customerIdAndToken = PreferenceUtils.getInstance()
				.getcustomerId(this);
		final String[] cat = customerIdAndToken.split("&");
		KkdHttpMagager.getInstance().tenderAffirmCampaign(poiId,
				(long) tenderAmout * 100, productType, new HttpCallBack() {

					@Override
					public void onSuccess(int statusCode, Object responseBody) {
						Message msg = new Message();
						msg.what = CAMPAIGN_SUCCESS;
						msg.obj = responseBody;
						mHandler.sendMessage(msg);
					}

					@Override
					public void onFailure(int statusCode, String desc) {

					}
				}, String.class);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			setResult(BACK_CODE);
			finish();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (dialog_finishShoutou != null) {
			dialog_finishShoutou.cancel();
			dialog_finishShoutou = null;
		}
	}
}
